package at.fhooe.SRWCProject.Bluetooth.Socket;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import at.fhooe.SRWCProject.Bluetooth.ChatActivity;
import at.fhooe.SRWCProject.MainActivity;

import java.util.UUID;

public class ConnectThread extends Thread{
    private BluetoothSocket mmBlueToothSocket;
    private final BluetoothDevice mmDevice;
    private final Handler mmHandler;
    private BluetoothAdapter mBluetoothAdapter;

    public ConnectThread(String address, Handler handler, UUID uuid){
        mmHandler = handler;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mmDevice = mBluetoothAdapter.getRemoteDevice(address);
        try{
            mmBlueToothSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
            ConnectionThread conn = new ConnectionThread(mmBlueToothSocket,mmHandler);
            mmHandler.obtainMessage(MainActivity.SOCKET_CONNECTED, conn).sendToTarget();
            conn.start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run(){
        //mBluetoothAdapter.cancelDiscovery();
        try{
            mmBlueToothSocket.connect();
        }catch (Exception e){
            try{
                mmBlueToothSocket.close();
            }catch (Exception ex){ex.printStackTrace();}
            e.printStackTrace();
        }
    }

}